<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? (parentDeptName ? `添加子部门 - ${parentDeptName}` : '添加部门') : '编辑部门'"
    width="600px"
    align-center
    :close-on-click-modal="false"
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="上级部门" prop="deptParentId">
        <ElTreeSelect
          v-model="formData.deptParentId"
          :data="deptTreeOptions"
          :props="treeProps"
          placeholder="请选择上级部门（不选则为顶级部门）"
          clearable
          check-strictly
          :render-after-expand="false"
          style="width: 100%"
        />
      </ElFormItem>

      <ElFormItem label="部门名称" prop="deptName">
        <ElInput
          v-model="formData.deptName"
          placeholder="请输入部门名称"
          maxlength="20"
          show-word-limit
        />
      </ElFormItem>

      <ElFormItem label="负责人" prop="deptManagerId">
        <ArtEmployeeSelect
          v-model="formData.deptManagerId"
          :multiple="false"
          :page-size="10"
          :only-enabled="true"
          :show-login-name="true"
          placeholder="请选择部门负责人"
          style="width: 100%"
        />
      </ElFormItem>

      <ElFormItem label="排序" prop="deptSort">
        <ElInputNumber
          v-model="formData.deptSort"
          :min="0"
          :max="10000"
          :step="1"
          placeholder="请输入排序值"
          style="width: 100%"
        />
      </ElFormItem>

      <ElFormItem label="部门描述" prop="deptDesc">
        <ElInput
          v-model="formData.deptDesc"
          type="textarea"
          :rows="4"
          placeholder="请输入部门描述"
          maxlength="300"
          show-word-limit
        />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" :loading="submitLoading" @click="handleSubmit" v-ripple>
          确定
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import {
    apiDeptSaveDataUsingPost,
    apiDeptUpdateDataUsingPost,
    type ApiDeptTreeVo
  } from '@/api'
  import ArtEmployeeSelect from '@/components/core/forms/art-employee-select/index.vue'

  interface Props {
    visible: boolean
    type: 'add' | 'edit'
    deptData?: ApiDeptTreeVo
    deptTree: ApiDeptTreeVo[]
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)
  const parentDeptName = computed(() => {
    if (props.type === 'add' && props.deptData) {
      return props.deptData.deptName
    }
    return ''
  })

  // 表单实例
  const formRef = ref<FormInstance>()
  const submitLoading = ref(false)

  // 部门树选项
  const deptTreeOptions = computed(() => {
    // 如果是编辑模式，需要过滤掉当前部门及其子部门
    if (props.type === 'edit' && props.deptData?.id) {
      return filterDeptTree(props.deptTree, props.deptData.id)
    }
    return props.deptTree
  })

  const treeProps = {
    children: 'children',
    label: 'deptName',
    value: 'id'
  }

  // 过滤部门树（排除当前部门及其子部门）
  const filterDeptTree = (tree: ApiDeptTreeVo[], excludeId: number): ApiDeptTreeVo[] => {
    return tree
      .filter((item) => item.id !== excludeId)
      .map((item) => ({
        ...item,
        children: item.children ? filterDeptTree(item.children, excludeId) : []
      }))
  }

  // 表单数据
  const formData = reactive({
    id: undefined as number | undefined,
    deptName: '',
    deptParentId: undefined as number | undefined,
    deptManagerId: null as number | null,
    deptSort: 0,
    deptDesc: ''
  })

  // 表单验证规则
  const rules: FormRules = {
    deptName: [
      { required: true, message: '请输入部门名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    deptSort: [
      { required: true, message: '请输入排序值', trigger: 'blur' },
      { type: 'number', min: 0, max: 10000, message: '排序值范围 0-10000', trigger: 'blur' }
    ]
  }



  // 初始化表单数据
  const initFormData = () => {
    const isEdit = props.type === 'edit' && props.deptData
    const isAddChild = props.type === 'add' && props.deptData
    const row = props.deptData

    if (isEdit && row) {
      Object.assign(formData, {
        id: row.id,
        deptName: row.deptName || '',
        // 当deptParentId为0时显示为空（表示顶级部门）
        deptParentId: row.deptParentId === 0 ? undefined : row.deptParentId,
        deptManagerId: row.deptManagerId || null,
        deptSort: row.deptSort || 0,
        deptDesc: row.deptDesc || ''
      })
    } else if (isAddChild && row) {
      // 添加子部门时，设置父部门ID
      Object.assign(formData, {
        id: undefined,
        deptName: '',
        deptParentId: row.id,
        deptManagerId: null,
        deptSort: 0,
        deptDesc: ''
      })
    } else {
      // 添加顶级部门
      Object.assign(formData, {
        id: undefined,
        deptName: '',
        deptParentId: undefined,
        deptManagerId: null,
        deptSort: 0,
        deptDesc: ''
      })
    }
  }

  // 统一监听对话框状态变化
  watch(
    () => [props.visible, props.type, props.deptData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      submitLoading.value = true

      let res
      if (dialogType.value === 'add') {
        // 添加部门
        res = await apiDeptSaveDataUsingPost({
          body: {
            deptName: formData.deptName,
            deptParentId: formData.deptParentId || 0,
            deptManagerId: formData.deptManagerId ?? undefined,
            deptSort: formData.deptSort,
            deptDesc: formData.deptDesc
          }
        })
      } else {
        // 编辑部门
        res = await apiDeptUpdateDataUsingPost({
          body: {
            id: formData.id,
            deptName: formData.deptName,
            deptParentId: formData.deptParentId || 0,
            deptManagerId: formData.deptManagerId ?? undefined,
            deptSort: formData.deptSort,
            deptDesc: formData.deptDesc
          }
        })
      }

      if (res) {
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
        dialogVisible.value = false
        emit('submit')
      } else {
        ElMessage.error('操作失败')
      }
    } catch (error: any) {
      if (error !== false) {
        console.error('提交部门数据失败:', error)
        ElMessage.error('操作失败')
      }
    } finally {
      submitLoading.value = false
    }
  }
</script>

<style lang="scss" scoped>
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
</style>
